const Base = require('./base.js'),
    wechatSerivce = think.service('wechat'),
	tokenService = think.service('token');

module.exports = class extends Base {
	/**
	 * @author: ares
	 * @date: 2018/6/1 15:56
	 * @description: 用户登录
	 */
	async loginAction() {
		let code = this.post('code'),
			userInfo = this.post('userInfo'),
			sendToken = await this.authLogin(code,userInfo);
		if (!sendToken.err){
			this.success({
				token:sendToken.token,
				userInfo:sendToken.sendUserInfo
			})
		}else{
			this.fail(sendToken.err)
		}
	}

	/**
	 * @author: ares
	 * @date: 2018/5/30 14:21
	 * @description: 验证用户登录
	 * @param {string}code       临时登录凭证
	 * @param {object}userInfo   登录时提交的数据，验证数据完整性或解密数据用
	 * @returns {Promise.<*>}
	 */
	async authLogin(code, userInfo) {
		let patient = this.model('patient'),
			sessionKey = '',
			openId = '',
			id = think.uuid('v4'),
			sendUserInfo = {};
		await wechatSerivce.getOpenIdAndSessionKey(code).then(res => {
			sessionKey = res.session_key,
				openId = res.openid;
		})

		if(!sessionKey || !openId) return {err:'获取openid失败'};

		if (!wechatSerivce.verifyDataIntegrity(userInfo,sessionKey)) return {err:'验证数据完整新失败'};

		let rows = await patient.selectPatientByOpenId(openId);

		if (!think.isEmpty(rows)) {
            sendUserInfo = rows;
		} else {
			await patient.addPatient({
				id: id,
				openid: openId,
				name: userInfo.userInfo.nickName,
				sex: userInfo.userInfo.gender,
				region:JSON.stringify([userInfo.userInfo.province,userInfo.userInfo.city,'']),
                avatarUrl:userInfo.userInfo.avatarUrl,
				create_time: ['exp', 'CURRENT_TIMESTAMP()']
			}).then(res=>{
                sendUserInfo = patient.selectPatientByOpenId(openId);
			});

		};
		let token = tokenService.createToken({id:openId});
		this.cache(openId, {
			token:token,
			sessionKey:sessionKey
		});
		return {
			err:false,
			token:token,
			sendUserInfo:sendUserInfo
        };
	}


    async updateUserInfoAction(){
		let self =this,
			openId = this.ctx.state.openid,
			info = this.post(),
			updateInfo = {
                real_name: info.name,
				sex: info.sex,
				phone: info.phone,
				birthday: info.birthday,
				region: JSON.stringify(info.region),
                update_time: ['exp', 'CURRENT_TIMESTAMP()']
			};
		await this.model('patient').updatePatientByOpenId(openId,updateInfo);
        let sendUpdateInfo= await this.model('patient').selectPatientByOpenId(openId);
        return self.success(sendUpdateInfo);
	}

	async logoutAction(){
		let token = this.header('token'),
			openid = await tokenService.verifyToken(token).data.id;
		this.cache(openid,null);
		this.success();
	}

    async updateServiceMsgAction(){
        let token = this.header('token'),
            decoded = await tokenService.verifyToken(token),
            patient = this.model('patient'),
			receiveServiceMsg = this.post(),
			sendServiceMsg = {};
        sendServiceMsg.time = think.datetime(new Date());
        sendServiceMsg.sender = 'service';
        sendServiceMsg.msg = '你发的消息 "' + receiveServiceMsg.msg + '" 已收到! 稍后会有客服与你取得联系!';
		let oldMsg = await patient.getServiceMsgByOpenId(decoded.data.id),
        	newMsg = think.isEmpty(oldMsg) ? [] : JSON.parse(oldMsg);
        newMsg.push(receiveServiceMsg);
        newMsg.push(sendServiceMsg);
        let updateMsg = await patient.updateServiceMsgByOpenId(decoded.data.id,{serviceMsg:JSON.stringify(newMsg)});
        if(updateMsg) this.success(sendServiceMsg);
	}

    async getServiceMsgAction(){
        let token = this.header('token'),
            decoded = await tokenService.verifyToken(token),
            patient = this.model('patient'),
        	sendServiceMsg = await patient.getServiceMsgByOpenId(decoded.data.id);
		this.success(sendServiceMsg);
    }
};
